package com.kingdee.pda.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.basecommon.http.MyObserver;
import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.PreferencesUtils;
import com.example.basecommon.utils.SpeakUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kingdee.pda.Api;
import com.kingdee.pda.MyApplication;
import com.kingdee.pda.R;
import com.kingdee.pda.adapter.ServerListAdapter;
import com.kingdee.pda.entity.LoginResponseBean;
import com.kingdee.pda.entity.ServerBean;
import com.kingdee.pda.ui.dialog.ServerAddressDialog;
import com.kingdee.pda.util.ApkTool;
import com.kingdee.pda.util.UpdateVersionUtil;
import com.kingdee.pda.util.WarehouseUtil;
import com.kingdee.pda.ui.popupwindow.ListSelectorPpWindow;
import com.kingdee.pda.util.ConstantPreference;
import com.kingdee.pda.util.FastClickUtil;
import com.example.basecommon.utils.LoginUtil;
import com.kingdee.pda.util.ToastUtils;
import com.tencent.bugly.beta.Beta;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录
 * Created by zhanlg
 * DATE 2021/5/20
 * TIME 19:51
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText mEtLoginAccount;
    private EditText mEtLoginName;
    private EditText mEtLoginPassword;
    private ImageView mIvSavePassword;
    private boolean isSavePassword = false;
    private List<String> mAccountList;
    private ArrayList<ServerBean> list;
    private AlertDialog alertDialog;
    private ServerListAdapter serverListAdapter;
    private TextView tv_versionCode;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onActivityCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initView() {
        mEtLoginAccount = ((EditText) findViewById(R.id.et_login_account));
        mEtLoginName = ((EditText) findViewById(R.id.et_login_name));
        mEtLoginPassword = ((EditText) findViewById(R.id.et_login_password));
        mIvSavePassword = ((ImageView) findViewById(R.id.iv_save_password));
        findViewById(R.id.iv_more_account).setOnClickListener(this);
        findViewById(R.id.ll_save_password).setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_selectServer).setOnClickListener(this);
        tv_versionCode = ((TextView) findViewById(R.id.tv_versionCode));
        tv_versionCode.setText(getResources().getString(R.string.app_name) + "：版本号" + ApkTool.getVersionCode(this));
    }

    @Override
    public void initData() {
        mAccountList = LoginUtil.getAccountCache();
        if (!mAccountList.isEmpty()) {
//            mEtLoginAccount.setText(mAccountList.get(0));
            mEtLoginName.setText(PreferencesUtils.getString(this, ConstantPreference.LOGIN_NAME, ""));
            mEtLoginPassword.setText(PreferencesUtils.getString(this, ConstantPreference.LOGIN_PASSWORD, ""));
            isSavePassword = PreferencesUtils.getBoolean(this, ConstantPreference.LOGIN_SAVE_PASSWORD, false);
            mIvSavePassword.setSelected(isSavePassword);
            mEtLoginName.setSelection(mEtLoginName.getText().length());
        }
    }

    @Override
    public void onClick(View v) {
        if (FastClickUtil.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_more_account:
                showAccoutSelectorPpWindow();
                break;
            case R.id.ll_save_password:
                isSavePassword = !isSavePassword;
                mIvSavePassword.setSelected(isSavePassword);
                break;
            case R.id.btn_login:
                doLogin();
                break;
            case R.id.btn_selectServer:
                showServerPickerDialog();
                break;
        }
    }

    /**
     * 展示账套账户选择悬浮框
     */
    private void showAccoutSelectorPpWindow() {
        if (mAccountList.isEmpty()) {
            ToastUtils.showShortOnDeepBg(this, "暂无账套记录");
            return;
        }
        ListSelectorPpWindow<String> accoutSelector = new ListSelectorPpWindow<>(LoginActivity.this,
                mEtLoginAccount.getWidth(),
                mAccountList,
                new ListSelectorPpWindow.onItemSelectedListener() {
                    @Override
                    public void onItemSelected(Object item) {
                        String account = ((String) item);
                        mEtLoginAccount.setText(account);
                    }
                });
        accoutSelector.showAsDropDown(mEtLoginAccount, 0, 10);
    }

    private void doLogin() {
        String serverUrl = PreferencesUtils.getServerUrl(this);
        if (TextUtils.isEmpty(serverUrl)) return;
        String loginName = mEtLoginName.getText().toString().trim();
        String loginPassword = mEtLoginPassword.getText().toString().trim();
        if (isDataValid(loginName, loginPassword)) {
            requestLogin("1", loginName, loginPassword);
        }
    }

    private void requestLogin(final String account, final String loginName, final String loginPassword) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", loginName);
        map.put("password", loginPassword);
        map.put("tenantid", account);
        map.put("logintype", String.valueOf(2));//传入int型会请求错误

        String dataBase = TextUtils.isEmpty(mEtLoginAccount.getText().toString()) ? "" : mEtLoginAccount.getText().toString();
        map.put("accountId", dataBase);

        MyObserver<LoginResponseBean> myObserver = new MyObserver<LoginResponseBean>(this) {
            @Override
            public void onSuccess(BaseResponse<LoginResponseBean> result) {
                loginFormat(result, account, loginName, loginPassword);
            }

            @Override
            public void onFailure(BaseResponse<LoginResponseBean> result, String msg) {
                loginFormat(result, account, loginName, loginPassword);
            }
        };
        HttpUtils.request(Api.class)
                .login(ConstantUtil.API_LOGIN, map)
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(myObserver);
    }

    private void loginFormat(BaseResponse<LoginResponseBean> result, String account, String loginName, String loginPassword) {
        LoginResponseBean data = result.data;
        if ("success".equals(result.state)) {
            boolean isSuccess = result.data.isSuccess();
            if (isSuccess) {
                String token = data.getAccess_token();
                String sessionId = data.getKERPSESSIONID();
                PreferencesUtils.putString(MyApplication.getInstance().getContext(), ConstantPreference.TOKEN, token);
                PreferencesUtils.putString(MyApplication.getInstance().getContext(), ConstantPreference.SESSIONID, token);

                LoginUtil.saveLoginInfo(account, loginName, loginPassword, isSavePassword);
                WarehouseUtil.clearWarehouseInfo();//登录需清除仓库缓存信息
                MainActivity.actionStart(LoginActivity.this);
                finish();
            } else {
                SpeakUtils.speakWithToast(LoginActivity.this, result.errorMsg, false, false);
            }
        } else {
            SpeakUtils.speakWithToast(LoginActivity.this, result.errorMsg, false, false);
        }
    }

    private void showServerPickerDialog() {
        //获取sp保存的服务器列表
        Gson gson = new Gson();
        Type type = new TypeToken<List<ServerBean>>() {
        }.getType();
        list = gson.fromJson(PreferencesUtils.getServerList(this), type);
        if (list == null) list = new ArrayList<>();
        //最后增加一条 添加服务器
        list.add(new ServerBean("添加服务器", ""));

        View view = LayoutInflater.from(this).inflate(R.layout.layout_simple_recyclerview, null);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        serverListAdapter = new ServerListAdapter(this, list);
        serverListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_edit:
                        ServerBean serverBean = list.get(position);
                        ServerAddressDialog.showInputAddressDialog(serverBean.getTitle(), serverBean.getUrl(), LoginActivity.this, new ServerAddressDialog.InputListener() {
                            @Override
                            public void okEvent(ServerBean serverAddress, DialogInterface dialog) {
                                serverBean.setTitle(serverAddress.getTitle());
                                serverBean.setUrl(serverAddress.getUrl());
                                dialog.dismiss();
                                PreferencesUtils.putServerList(LoginActivity.this, new Gson().toJson(list.subList(0, list.size() - 1)));
                                serverListAdapter.notifyDataSetChanged();
                            }
                        });
                        break;
                    case R.id.item:
                        //点击最后一条进行添加操作，点击其他条则为选中服务器
                        if (position == list.size() - 1) {
                            ServerAddressDialog.showInputAddressDialog("", " https://", LoginActivity.this, new ServerAddressDialog.InputListener() {
                                @Override
                                public void okEvent(ServerBean serverAddress, DialogInterface dialog) {
                                    for (ServerBean bean : list) {
                                        if (serverAddress.getUrl().equals(bean.getUrl()) && serverAddress.getTitle().equals(bean.getTitle())) {
                                            SpeakUtils.speakWithToast(LoginActivity.this, "此服务器已存在！", false, false);
                                            return;
                                        }
                                    }
                                    list.add(list.size() - 1, serverAddress);
                                    dialog.dismiss();
                                    PreferencesUtils.putServerList(LoginActivity.this, new Gson().toJson(list.subList(0, list.size() - 1)));
                                    serverListAdapter.notifyDataSetChanged();
                                }
                            });
                        } else {
                            PreferencesUtils.putServerCount(LoginActivity.this, position);
                            PreferencesUtils.putServerUrl(LoginActivity.this, list.get(position).getUrl());
                            alertDialog.dismiss();
                        }
                        break;
                }
            }
        });
        serverListAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    if (position != list.size() - 1) {
                        list.remove(position);
                    }
                    PreferencesUtils.putServerList(LoginActivity.this, new Gson().toJson(list.subList(0, list.size() - 1)));

                    serverListAdapter.notifyDataSetChanged();
                    SpeakUtils.speakWithToast(LoginActivity.this, "删除服务器成功！", false, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        recyclerView.setAdapter(serverListAdapter);
        serverListAdapter.notifyDataSetChanged();
        alertDialog = new AlertDialog.Builder(LoginActivity.this, R.style.login_AlertDialogStyle)
                .

                        setCancelable(true)
                .

                        setView(view)
                .

                        setTitle("切换服务器")
                .

                        create();
        alertDialog.show();
    }

    private boolean isDataValid(String loginName, String loginPassword) {
        if (TextUtils.isEmpty(loginName)) {
            ToastUtils.showShortOnDeepBg(this, "请输入账号！");
            return false;
        }
        if (TextUtils.isEmpty(loginPassword)) {
            ToastUtils.showShortOnDeepBg(this, "请输入密码！");
            return false;
        }
        return true;
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onNetworkAvailable() {

    }

    @Override
    protected void onNetworkError() {
        ToastUtils.showLongOnDeepBg(LoginActivity.this, "网络连接失败");
    }
}
